import { messages, queryCurrencyPrecision, dealListTag } from "share/common";
import React from "react";
import ExportModal from "components/template/export-modal/export-modal";
import { connect } from "react-redux";
import { message, Popover, Alert, Tabs, Select, Tag, Checkbox } from "antd";
const TabPane = Tabs.TabPane;
const Option = Select.Option;
import moment from "moment";
import menuRoute from "routes/menuRoute";
import constants from "share/constants";
import financeViewService from "containers/financial-management/expense-view/expense-view.service";
import borrowService from "containers/loan-billing/borrow-and-return.service";
import CostCenterSearchForm from "components/template/cost-center-search-form/cost-center-search-form";
import "styles/financial-management/expense-view/expense-view.scss";
import BatchDownload from "./batch-download";
import AdvancedTable from "components/advanced-table";
import GenerateBatch from "./generate-batch";
import selectorData from "share/selectorData";
import SelectBatchNumber from "./select-batch-number";
import NumberRange from "containers/financial-management/expense-view/component/number-range";
import expBagCode from "../new-finance-audit/searchForm-components/expBagCode";

class FinanceView extends React.Component {
  print = (record, event) => {
    event.preventDefault();
    event.stopPropagation();
    event.cancelBubble = true;
    if (record.entityType === 1002) {
      financeViewService.printExpenseReport(record.entityOID).then((res) => {
        window.open(res.data.fileURL, "_blank");
      });
    } else {
      borrowService.printLoanApplication(record.entityOID).then((res) => {
        window.open(res.data.link, "_blank");
      });
    }
  };

  columns = [
    {
      title: messages("financial-management.key130" /*工号*/),
      dataIndex: "employeeID",
    },
    {
      title: messages("financial-management.key131" /*申请人*/),
      dataIndex: "applicant",
    },
    {
      title: messages("financial-management.key132" /*提交日期*/),
      dataIndex: "lastSubmittedDate",
      width: 95,
      render: (date, record) =>
        moment(date || record.createDate).format("YYYY-MM-DD"),
      sorter: true,
    },
    {
      title: messages("financial-management.key133" /*单据类型*/),
      dataIndex: "formName",
      render: (value) => <Popover content={value}>{value}</Popover>,
      sorter: true,
    },
    {
      title: messages("financial-management.key134" /*单号*/),
      dataIndex: "businessCode",
      render: (value, record) => (
        <Popover
          content={
            record.parentBusinessCode
              ? `${record.parentBusinessCode} - ${value}`
              : value
          }
        >
          {record.parentBusinessCode
            ? `${record.parentBusinessCode} - ${value}`
            : value}
        </Popover>
      ),
      sorter: true,
    },
    {
      title: messages("expense-1.key389") /*发票袋编号*/,
      dataIndex: "expBagCode",
      width: 120,
    },
    {
      title: messages("common.matter") /*事由*/,
      dataIndex: "title",
      width: 120,
      render: (value) => (
        <Popover content={value} placement="topLeft">
          {value}
        </Popover>
      ),
    },
    {
      title: messages("financial-management.key136" /*总金额*/),
      dataIndex: "totalAmount",
      align: "right",
      render: (value, record) =>
        this.filterMoney(value, queryCurrencyPrecision(record.currencyCode)),
      sorter: true,
    },
    {
      title: messages("financial-management.key135" /*币种*/),
      dataIndex: "currencyCode",
      width: 48,
    },
    {
      title: messages("financial-management.key952") /*收单状态*/,
      dataIndex: "receiveStatus",
      width: 48,
      hide: true,
      render: (value) =>
        constants.getTextByValue(String(value + ""), "receiptOptions", "label"),
    },
    {
      title: "ap凭证编号",
      dataIndex: "origDocumentSequence",
      width: "7%",
      render: (value) =>
        value ? (
          <Popover content={value} placement="topLeft">
            {value}
          </Popover>
        ) : (
          "-"
        ),
    },
    {
      title: "gl凭证编号",
      dataIndex: "origDocumentSequenceGl",
      width: "7%",
      render: (value) =>
        value ? (
          <Popover content={value} placement="topLeft">
            {value}
          </Popover>
        ) : (
          "-"
        ),
    },
    {
      title: messages("financial-management.key799") /*批量打印批次号*/,
      dataIndex: "expenseReportBatchId",
      render: (value) =>
        value ? (
          <Popover content={value} placement="topLeft">
            {value}
          </Popover>
        ) : (
          "-"
        ),
    },
    {
      title: messages("budget.key25") /*审核状态*/,
      dataIndex: "currentChainStatus",
      render: (value) =>
        value ? (
          <Popover content={value} placement="topLeft">
            {value}
          </Popover>
        ) : (
          "-"
        ),
    },
    {
      title: messages("common.column.status"),
      dataIndex: "status",
      width: this.props.language.code === "zh_cn" ? "8%" : "13%",
      render: (value, record) => (
        <Tag
          color={
            constants.getTextByValue(
              String(value + "" + record.rejectType),
              "documentStatusExpenseView",
              "color"
            ) ||
            constants.getTextByValue(String(value), "documentStatusExpenseView", "color")
          }
        >
          {constants.getTextByValue(
            String(value + "" + record.rejectType),
            "documentStatusExpenseView"
          ) || constants.getTextByValue(String(value), "documentStatusExpenseView")}
        </Tag>
      ),
    },
    {
      title: messages("common.operation"),
      dataIndex: "operation",
      width: 50,
      render: (value, record) => (
        <a onClick={(event) => this.print(record, event)}>
          {messages("financial-management.key137" /*打印*/)}
        </a>
      ),
    },
  ];

  autoAuditOptions = [
    { label: messages("financial-management.key139" /*全部*/), value: null },
    { label: messages("common.yes") /*是*/, value: true },
    { label: messages("common.no") /*否*/, value: false },
  ];

  state = {
    sort: "",
    searchParams: {},
    tabKey: "view",
  };

  statusOptions = [
    {
      label: messages("financial-management.key120" /*审批中*/),
      value: "submitted",
    },
    // {
    //   label: messages("financial-management.key121" /*已通过*/),
    //   value: "approval_pass",
    // },
    {
      label: messages("financial-management.key122" /*已驳回*/),
      value: "approval_reject",
    },
    {
      label: messages("components.key1348" /*复审通过*/),
      value: "audit_pass",
    },
    {
      label: messages("financial-management.key227" /*审核驳回*/),
      value: "audit_reject",
    },
    {
      label: messages("financial-management.key232" /*付款中*/),
      value: "payment_in_process",
    },
    {
      label: messages("financial-management.key174" /*已付款*/),
      value: "finance_loan",
    },
    {
      label: messages("components.key1324" /*预审通过*/),
      value: "audit_review_passed",
    },
    {
      label: messages("financial-management.key1251" /*待预审*/),
      value: "auditReview",
    },
  ];

  searchForm = [
    {
      id: "formOIDs",
      component: "Searcher",
      label: messages("financial-management.key176" /*表单类型*/),
      props: {
        type: "authority_form",
        listExtraParams: { formType: 1002 },
        labelKey: "formName",
        descriptionKey: "companyName",
      },
      parser: (value) => ({
        formOIDs: value ? value.map((item) => item.formOID) : null,
      }),
    },
    {
      id: "userOID",
      label: messages("components.key1371" /*申请人姓名/工号/eid*/),
      component: "Selector",
      props: {
        placeholder:
          messages("common.please.enter") +
          messages("components.key1371" /*申请人姓名/工号/eid*/),
        type: "user_all",
        selectorItem: {
          ...selectorData["user_all"],
          url: `/api/public/getAllUser?page=0&size=9999&roleType=TENANT&status=all`,
          label: (record) =>
            `${record.employeeID}-${record.fullName}${
              record.status !== 1001
                ? `（${
                    record.status === 1002
                      ? messages("financial-management.key622") /*待离职员工*/
                      : messages("financial-management.key623") /*离职员工*/
                  }）`
                : ""
            }`,
        },
        searchIfKeywordIsNull: true,
      },
    },
    {
      id: "businessCode",
      label: messages("financial-management.key234" /*单据ID*/),
      component: "Selector",
      props: {
        type: "expense_report_id",
        params: {
          entityType: "1002",
        },
      },
    },
    {
      id: "departmentOIDs",
      label: messages("financial-management.key195" /*部门*/),
      component: "Chooser",
      props: {
        type: "department",
        labelKey: "name",
        valueKey: "departmentOid",
      },
      parser: (value) => ({
        departmentOIDs: value ? value.map((item) => item.departmentOid) : null,
      }),
      JSONObjectFormatterParams: ["name", "departmentOid"],
    },
    {
      id: "submittedDate",
      label: messages("financial-management.key132") /*提交日期*/,
      component: "DateRangePicker",
      initialValue: [moment().subtract(1, "month"), moment()],
      parser: (value) => ({
        beginDate:
          value && value[0]
            ? moment(value[0]).format("YYYY-MM-DD 00:00:00")
            : null,
        endDate:
          value && value[1]
            ? moment(value[1]).format("YYYY-MM-DD 23:59:59")
            : null,
      }),
    },
    {
      id: "approvalDate",
      label: messages("financial-management.key895") /*审批日期*/,
      component: "DateRangePicker",
      parser: (value) => ({
        approvalStartDate:
          value && value[0]
            ? moment(value[0]).format("YYYY-MM-DD 00:00:00")
            : null,
        approvalEndDate:
          value && value[1]
            ? moment(value[1]).format("YYYY-MM-DD 23:59:59")
            : null,
      }),
    },
    {
      id: "auditedApprovalDate",
      label: messages("financial-management.key564" /*审核日期*/),
      component: "DateRangePicker",
      parser: (value) => ({
        auditedApprovalStartDate:
          value && value[0]
            ? moment(value[0]).format("YYYY-MM-DD 00:00:00")
            : null,
        auditedApprovalEndDate:
          value && value[1]
            ? moment(value[1]).format("YYYY-MM-DD 23:59:59")
            : null,
      }),
    },
    {
      id: "searchCorporations",
      label: messages("financial-management.key128" /*法人实体*/),
      component: "Chooser",
      props: {
        type: "legal_entity",
        labelKey: "entityName",
        valueKey: "companyReceiptedOID",
        listKey: "rows",
      },
      parser: (value) => ({
        searchCorporations: value
          ? value.map((item) => item.companyReceiptedOID)
          : null,
      }),
      JSONObjectFormatterParams: ["entityName", "companyReceiptedOID"],
    },
    {
      id: "autoAudit",
      label: messages("financial-management.key238" /*自动审核通过*/),
      component: (
        <Select
          placeholder={messages("common.select") /*"请选择"*/}
          style={{ width: "100%" }}
        >
          {this.autoAuditOptions.map((item) => (
            <Option key={item.value}>{item.label}</Option>
          ))}
        </Select>
      ),
      parser: (value) => {
        let result = {
          autoAudit: null,
        };
        if (typeof value === "string") {
          switch (value) {
            case "true":
              result.autoAudit = true;
              break;
            case "false":
              result.autoAudit = false;
              break;
            case "null":
              result.autoAudit = null;
              break;
            default:
          }
        }
        return result;
      },
      tagParser: (value) =>
        this.autoAuditOptions.find((item) => item.value + "" === value).label,
    },
    {
      id: "searchCostCenterCommands",
      label: messages("financial-management.key145" /*成本中心*/),
      component: (
        <CostCenterSearchForm
          title={messages("financial-management.key145" /*成本中心*/)}
        />
      ),
      tagParser: (value) =>
        messages(
          "common.total.selected",
          { total: value.length } /*已选total条*/
        ),
    },
    {
      id: "batchNumber",
      label: messages("financial-management.key799") /*批量打印批次号*/,
      component: <SelectBatchNumber />,
      parser: (value) => {
        if (!value) return null;
        const { existsExpenseReportBatchId, expenseReportBatchId } = value;
        return existsExpenseReportBatchId && !expenseReportBatchId
          ? null
          : !existsExpenseReportBatchId
          ? { existsExpenseReportBatchId }
          : { expenseReportBatchId, existsExpenseReportBatchId };
      },
      tagParser: ({ existsExpenseReportBatchId, expenseReportBatchId }) =>
        !existsExpenseReportBatchId
          ? messages("financial-management.key604") /*为空*/
          : expenseReportBatchId,
    },
    {
      id: "labelIds",
      label: messages("financial-management.key574") /*单据标签*/,
      component: "Searcher",
      props: {
        labelKey: "name",
        type: "expense_label",
        listExtraParams: { labelCategory: 1 },
      },
      parser: (value) => ({
        labelIds: value ? value.map((item) => item.id) : null,
      }),
      JSONObjectFormatterParams: ["id", "name"],
    },
    {
      id: "receiveStatus",
      label: messages("financial-management.key952") /*收单状态*/,
      component: (
        <Select
          placeholder={messages("common.select") /*"请选择"*/}
          style={{ width: "100%" }}
        >
          {constants.receiptOptions.map((item) => (
            <Option key={item.value}>{item.label}</Option>
          ))}
        </Select>
      ),
      tagParser: (value) =>
        value
          ? constants.receiptOptions.filter((item) => item.value == value)[0]
              .label
          : null,
    },
    {
      id: "financeReceiptDateRange",
      label: messages("financial-management.key896") /*收单日期*/,
      component: "DateRangePicker",
      parser: (value) => ({
        financeReceiveStartDate:
          value && value[0]
            ? moment(value[0]).format("YYYY-MM-DD 00:00:00")
            : null,
        financeReceiveEndDate:
          value && value[1]
            ? moment(value[1]).format("YYYY-MM-DD 23:59:59")
            : null,
      }),
    },
    {
      id: "reimbursementBatchId",
      label: messages("financial-management.key768") /*付款批次号*/,
      component: "Selector",
      props: {
        placeholder:
          messages("common.please.enter") +
          messages("financial-management.key768") /*付款批次号*/,
        type: "reimbursement_batch",
        params: {
          batchType: 3001,
          roleType: "TENANT",
        },
      },
      JSONObjectFormatterParams: ["reimbursementBatchName", "id"],
    },
    {
      id: "numberRange",
      label: messages("financial-management.key953") /*金额范围*/,
      component: <NumberRange />,
      parser: (value) => ({
        minTotalAmount: value && value[0] ? value[0] : null,
        maxTotalAmount: value && value[1] ? value[1] : null,
      }),
      tagParser: (value) =>
        value &&
        (value[0] || value[1]) &&
        `${value[0] === 0 ? value[0] : value[0] || ""} ~ ${
          value[1] === 0 ? value[1] : value[1] || ""
        }`,
    },
    expBagCode,
    {
      id: "status",
      label: messages("budget.key25" /*审核状态*/),
      component: (
        <Checkbox.Group>
          {this.statusOptions
            .concat(
              this.props.profile["finance.payment.cancel"]
                ? {
                    label: messages("financial-management.key571") /*取消支付*/,
                    value: "pay_cancel",
                  }
                : []
            )
            .map((item) => (
              <Checkbox key={item.value} value={item.value}>
                {item.label}
              </Checkbox>
            ))}
        </Checkbox.Group>
      ),
      tagParser: (value) =>
        this.statusOptions
          .filter((item) => value.find((key) => item.value === key))
          .map((item) => item.label)
          .join(","),
      row: true,
    },
  ];

  service = (page, size, searchParams) => {
    const { sort } = this.state;
    if (sort) {
      searchParams.sorts = {
        property: sort.split(",")[0],
        direction: sort.split(",")[1],
      };
    }
    searchParams.entityType = 1002;
    let isAudit = '1';
    let arr = []
    if (searchParams.status && searchParams.status.length > 0) {
      if (searchParams.status.includes('auditReview')) {
        arr = searchParams.status.filter(item => item !== 'auditReview')
        searchParams.auditReview = true;
      } else {
        arr = searchParams.status
      }
    }
    console.log('arr', arr)
    searchParams.status = arr;
    return financeViewService.getFinanceViewList(page, size, searchParams, isAudit);
  };

  expenseDetailView = menuRoute.getRouteItem(
    "expense-report-detail-view",
    "key"
  );
  loanDetailView = menuRoute.getRouteItem("loan-detail-view", "key");

  handleRowClick = (record) => {
    let url = "";
    if (record.entityType === 1002) {
      url = this.expenseDetailView.url.replace(
        ":expenseReportOID",
        record.entityOID
      ).replace(':tab', 'finance-view-expense');
    } else {
      url = this.loanDetailView.url
        .replace(":formOID", record.formOID)
        .replace(":loanBillOID", record.entityOID);
    }
    window.open(url);
  };

  handleSortChange = (pagination, filter, sorter) => {
    let sort = "";
    if (sorter.order) {
      sort = `${sorter.columnKey},${
        sorter.order === "ascend" ? "ASC" : "DESC"
      }`;
    }
    this.setState({ sort }, this.advancedTableRef.getList);
  };

  onGetData = (dataSource, pagination, searchParams) => {
    this.setState({ searchParams });
  };

  render() {
    const { searchParams, tabKey } = this.state;
    return (
      <div className="expense-view full-height-page">
        <Tabs type="card" onChange={(tabKey) => this.setState({ tabKey })}>
          <TabPane
            tab={messages("financial-management.key605") /*报销单查看*/}
            key="view"
          >
            <AdvancedTable
              index
              onRef={(ref) => (this.advancedTableRef = ref)}
              title={messages("financial-management.key605") /*报销单查看*/}
              columns={this.columns}
              searchForm={this.searchForm}
              service={this.service}
              onRow={(record) => ({
                onClick: () => this.handleRowClick(record),
              })}
              expandedRowRender={dealListTag}
              expandAll
              onChange={this.handleSortChange}
              rowKey={(record) => record.entityOID}
              tableName="expense-view"
              onGetData={this.onGetData}
              pinnedList={["businessCode", "userOID", "status"]}
              footer={
                <span>
                  {/* <ExportModal
                    type="btn"
                    btnType="primary"
                    exportTitle={messages(
                      "financial-management.key146"
                    )}
                    exportType="BILL_CHECK"
                    exportCondition={{
                      billCheckSearchCommand: searchParams,
                    }}
                    exportCommand={"EXP_OR_LOANBILL"}
                  />
                  &nbsp;&nbsp; */}
                  <GenerateBatch
                    searchParams={searchParams}
                    onCreate={() => this.advancedTableRef.getList()}
                  />
                </span>
              }
            >
              <Alert
                className="notice"
                type="info"
                showIcon
                message={
                  <div
                    dangerouslySetInnerHTML={{
                      __html: messages("financial-management.key620"),
                      /*列表中<span class='color-blue'>批量打印批次号为空</span>的数据将会生成批次。*/
                    }}
                  />
                }
              />
            </AdvancedTable>
          </TabPane>
          <TabPane
            tab={messages("financial-management.key607") /*批次下载*/}
            key="download"
          >
            <BatchDownload tabKey={tabKey} />
          </TabPane>
        </Tabs>
      </div>
    );
  }
}

FinanceView.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    user: state.login.user,
    language: state.main.language,
    profile: state.login.profile,
  };
}

export default connect(mapStateToProps)(FinanceView);
